using Supremacy.Scripting.Runtime;

namespace Supremacy.Scripting.Ast
{
    public class UsingEntry
    {
        public FullNamedExpression Name { get; set; }

        protected FullNamedExpression Resolved { get; set; }

        public UsingEntry Clone(CloneContext cloneContext)
        {
            return new UsingEntry
                   {
                       Name = Ast.Clone(cloneContext, this.Name),
                       Resolved = Ast.Clone(cloneContext, this.Resolved)
                   };
        }

        public string GetSignatureForError()
        {
            return this.Name.GetSignatureForError();
        }

        public override string ToString()
        {
            return this.GetSignatureForError();
        }

        public virtual FullNamedExpression Resolve(ParseContext rc)
        {
            if (this.Resolved != null)
                return this.Resolved as NamespaceExpression;

            var memberAccess = this.Name as MemberAccessExpression;
            if (memberAccess != null)
                this.Resolved = memberAccess.ResolveNamespaceOrType(rc, false);
            else
                this.Resolved = this.Name.Resolve(rc) as FullNamedExpression;

            if (this.Resolved == null)
            {
                rc.ReportError(
                    138,
                    string.Format(
                        "'{0}' is a type, not a namespace.  A using namespace directive can only be applied to namespaces.",
                        this.GetSignatureForError()),
                    this.Name.Span);
            }

            return this.Resolved;
        }
    }

    public class UsingAliasEntry : UsingEntry
    {
        public string Alias { get; set; }

        public override FullNamedExpression Resolve(ParseContext rc)
        {
            if (this.Resolved != null || this.Name == null)
                return this.Resolved;

            if (rc == null)
                return null;

            base.Resolve(rc);
            
            if (this.Resolved == null)
            {
                this.Name = null;
                return null;
            }

            if (this.Resolved is TypeExpression)
                this.Resolved = this.Resolved.ResolveAsBaseTerminal(rc, false);

            return this.Resolved;
        }

        public override string ToString()
        {
            return string.Format("{0} = {1}", this.Alias, this.Name.GetSignatureForError());
        }
    }
}